package job.manager.client.mb;

import com.icesoft.faces.component.menubar.MenuItem;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.PostConstruct;
import javax.faces.context.FacesContext;
import javax.servlet.ServletContext;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.springframework.security.GrantedAuthority;
import org.springframework.security.context.SecurityContextHolder;

/**
 *  The Navigation ManagedBean is responsible for loading the menu xml and create
 *  a list to be passed to the iceface menu.
 * 
 */
public class NavigationMB {

    private List<MenuItem> list;

    /** Creates a new instance of NavigationMB */
    public NavigationMB() {
        onInit();
    }

    @PostConstruct
    public void onInit() {
        list = null;
    }

    // creates the menu
    private List<MenuItem> createMenu() {
        List<MenuItem> menuList = new ArrayList<MenuItem>();
        try {
            //looking up the real path to the file
            ServletContext context = (ServletContext)FacesContext.getCurrentInstance().getExternalContext().getContext();
            String path = context.getRealPath("/");
            //get what role the user is
            GrantedAuthority[] auth = SecurityContextHolder.getContext().getAuthentication().getAuthorities();
            String role = auth[0].getAuthority();
            // loads the file depending on role
            File f = new File(path + "WEB-INF\\" + role + "\\menuList.xml"); //the menu is forcerd to be named menuList.xml and be put in the correct directory
            //if file exists create menu
            if( f.exists() ) {
                //create a parser
                SAXBuilder parser = new SAXBuilder();
                //build the jdom
                Document doc = parser.build(f);
                List<Element> elements = doc.getRootElement().getChildren();
                //create a menu ite for each child in the jdom document
                for( org.jdom.Element e : elements) {
                    MenuItem m = new MenuItem();
                    m.setValue(e.getAttributeValue("key"));
                    m.setLink(e.getAttributeValue("value"));
                    menuList.add(m);

                }
            }
        } catch (JDOMException ex) {
            Logger.getLogger(NavigationMB.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(NavigationMB.class.getName()).log(Level.SEVERE, null, ex);
        }
        return menuList;        
    }

    public List<MenuItem> getList() {
        if (this.list == null) {
            list = this.createMenu();
        }
        return list;
    }


}
